package com.share.thread;

/**
 * @desc:
 * @author:caifan
 * @date:2022/4/5
 */
public class ShowCAS implements Runnable {
    private volatile int value;

    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;
        if (expectedValue == oldValue) {
            System.out.println(Thread.currentThread().getName() + "执行成功");
            value = newValue;
        }
        return oldValue;
    }

    @Override
    public void run() {
        compareAndSwap(100, 150);
    }

    public static void main(String[] args) throws InterruptedException {
        ShowCAS showCAS = new ShowCAS();
        showCAS.value = 100;
        Thread t1 = new Thread(showCAS, "thread1");
        Thread t2 = new Thread(showCAS, "thread2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(showCAS.value);
    }
}
